package com.mc.code.web.sys;

import com.mc.code.entity.sys.SysMenu;
import com.mc.code.entity.sys.SysUser;
import com.mc.code.mapper.SysUserMapper;
import com.mc.code.sysService.SysMenuService;
import com.mc.code.sysService.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
@Controller
public class AdminLoginController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;

    @RequestMapping("/syslogin")
    public String syslogin(){
        return "/sys/adminLogin";
    }

    @RequestMapping("/sysloginfailed")
    public String sysloginfailed(){
        return "/sys/adminLoginFailed";
    }

    @RequestMapping("/")
    public String adminLogin(Model model, HttpServletRequest request, HttpSession session){
//        查找管理员姓名
        /*获取登录用户信息 s*/
        UserDetails userDetails=null;
        try {
            userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        catch (Exception e){
            return "0";
        }
        //根据用户登录查询对应的菜单userDetails.getUsername()获取adminName
        String username= userDetails.getUsername();
        List<SysMenu> menus = sysMenuService.findMenuByAdminNo(username);
        System.out.println(username);
        model.addAttribute("username",username);
        model.addAttribute("menus",menus);
        SysUser sysUser = sysUserService.findUserByName(username);
        session.setAttribute("admin",sysUser);
        return "/sys/home";
    }
    //跳转到修改密码页面
    @RequestMapping("/modifyAdminPwd")
    public String modifyAdminPwd(){
        System.out.println("11111");
        return "/sys/modifyAdminPwd";
    }

    //提交密码进行修改
    @RequestMapping("/submitPwd")
    @ResponseBody
    public String sumbitPwd(SysUser sysUser){
        System.out.println("修改的信息"+sysUser);
        //管理员自己修改密码 根据adminNo进行修改
        //修改前将新密码进行加密
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        sysUserService.updateUser(sysUser);
        return "success";
    }

    //退出登录
    @RequestMapping("/syslogout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/syslogin";
    }

}
